use regex::Regex;
use std::num::ParseIntError;

const NUM_DICT: [char; 16] = [
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f',
];

pub fn convert_base(num_str: &str, to_base: u32) -> String {
    // 首先解析num_str, 然后将num_str转化为十进制，再转化为to_base进制
    if let Ok((num_str_new, base)) = parse_num_str(num_str) {
        let num = convert_base_to_decimal(num_str_new, base).unwrap();
        println!("num: {}", num);
        return convert_decimal_to_base(num, to_base);
    } else {
        return "Invalid input".to_string();
    }
}

//将num_str解析为(num: &str, base: u32)
pub fn parse_num_str(num_str: &str) -> Result<(String, u32), String> {
    // TODO: 这里写逻辑
    let re = Regex::new(r"(?<num_str>.+)\((?<base>\d+)\)").unwrap();
    if let Some(cap) = re.captures(num_str) {
        let num_str = cap.name("num_str").unwrap().as_str();
        let base = cap.name("base").unwrap().as_str().parse::<u32>().unwrap();
        return Ok((num_str.to_string(), base));
    } else {
        return Err("Invalid input string".to_string());
    }
}
//(num: String, base: u32)转化为十进制数
pub fn convert_base_to_decimal(num_str: String, base: u32) -> Result<i32, ParseIntError> {
    // TODO: 这里写逻辑
    i32::from_str_radix(&num_str, base)
}

//将十进制数转为任意进制
pub fn convert_decimal_to_base(num: i32, to_base: u32) -> String {
    // TODO: 这里写逻辑
    let mut num = num;
    let mut result = String::new();
    while num > 0 {
        let remainder = num % to_base as i32;
        result.push(NUM_DICT[remainder as usize]);
        num /= to_base as i32;
    }
    result.chars().rev().collect()
}
